package com.probiz.estoresa.eai.log.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.eai.log.EaiJobLog;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.eai.log.service.EaiJobLogManager;

public class EaiJobLogController extends GenericStoreAdminController<EaiJobLog> {
    private EaiJobLogManager eaiJobLogManager = null;
    
    private Scheduler eaiScheduler = null;

    public void setEaiScheduler(Scheduler eaiScheduler) {
		this.eaiScheduler = eaiScheduler;
	}

	public void setEaiJobLogManager(EaiJobLogManager inMgr) {
        this.eaiJobLogManager = inMgr;
    }

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(EaiJobLog entity) {
		return entity.getEaiJobLogName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = eaiJobLogManager;
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, EaiJobLog entity, BindException errors) {
	}

	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, List<String>> groupMap = new HashMap<String, List<String>>();
		try	{
			String[] triggerGroups = eaiScheduler.getTriggerGroupNames();
			int groupSize = triggerGroups.length;
			for (int i = 0; i < groupSize; i++)	{
				String[] triggersInGroup = eaiScheduler.getTriggerNames(triggerGroups[i]);
				List<String> groupDotNameList = new ArrayList<String>();
				for (int j = 0; j < triggersInGroup.length; j++){
					Trigger trigger = eaiScheduler.getTrigger(triggersInGroup[j], triggerGroups[i]);
					groupDotNameList.add(trigger.getFullName());
				}
				
				groupMap.put(triggerGroups[i], groupDotNameList);
			}
		}catch (SchedulerException e){
			logger.error("Get scheduler fail.",e);
		}
		
		request.getSession().setAttribute("groupMap", groupMap);
		
		return super.defaultAction(request, response);
	}

}
